package cn.usian.basicInformation.log.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.usian.basicInformation.log.mapper.LogMapper;
import cn.usian.basicInformation.log.service.ILogService;
import cn.usian.dto.basicInformation.log.BaseOperationLogDto;
import cn.usian.pojo.Result;
import cn.usian.pojo.basicInformation.log.BaseOperationLog;
import cn.usian.vo.basicInformation.log.BaseOperationLogVo;
import cn.usian.vo.basicInformation.log.LogVo;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/log")
@Slf4j
public class LogController {
    @Autowired
    private ILogService logService;
    @Autowired
    private LogMapper logMapper;

    @GetMapping("/list")
    public Result getLogList(BaseOperationLogDto logDto){
        log.info("logDto:{}",logDto);
        PageInfo<BaseOperationLogVo> list = logService.list(logDto);
        return Result.ok(list);
    }

    @PostMapping("/save")
    public Result save(@RequestBody BaseOperationLog logInfo){
        logService.save(logInfo);
        return Result.ok();
    }

    @GetMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response) throws IOException {
        List<BaseOperationLogVo> list = logMapper.list(null);
        List<LogVo> excel = new ArrayList<>();
        list.forEach(item->{
            LogVo logVo = new LogVo();
            BeanUtil.copyProperties(item,logVo);
            logVo.setUpdateTime(item.getUpdateTime());
            logVo.setOperationType(item.getOperationType()==1?"新增":"修改");
            excel.add(logVo);
        });
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("操作日志", "utf-8");
        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" +
                filename + ".xlsx");
            EasyExcel.write(response.getOutputStream(),LogVo.class)
                    // 设置excel文件的格式
                    .excelType(ExcelTypeEnum.XLSX)
                    // 从第几列开始写
                    .sheet(0)
                    // 执行写的操作,将实体类集合告知,写excelList
                    .doWrite(excel);
    }

}
